/* eslint-disable operator-assignment */
import React, { useState, useEffect } from 'react';
import { Tabs, Button } from 'antd';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';

import { findTopReport, getGuide } from '@/pages/scale/service/compose';

import { truncate } from 'lodash';
import { printFile } from '@/services/common';
import { arrTrans } from '@/utils/utils';
import { getEvaluationSingle } from '../service';

import S0062_Chart1 from './S0062/Chart1';
import S0062_Chart2 from './S0062/Chart2';
import S0062_Chart3 from './S0062/Chart3';
import S0062_Chart4 from './S0062/Chart4';
import S0062_Chart5 from './S0062/Chart5';
import S0062_Chart6 from './S0062/Chart6';
import S0062_Chart7 from './S0062/Chart7';
import S0062_Chart8 from './S0062/Chart8';

import S0075_Chart1 from './S0075/Chart1';
import S0075_Chart2 from './S0075/Chart2';
import S0075_Chart3 from './S0075/Chart3';
import S0075_Chart4 from './S0075/Chart4';
import S0075_Chart5 from './S0075/Chart5';
import S0075_Chart6 from './S0075/Chart6';
import S0075_Chart7 from './S0075/Chart7';
import S0075_Chart8 from './S0075/Chart8';

const getQuestion = (map, no) => {
  const q = map[no];

  if (q) {
    const { objectAnswer, answerOptions, questionInfo } = q;
    const index = answerOptions.findIndex((e) => e.option === objectAnswer * 1);

    let result = {};

    if (questionInfo && questionInfo.trim().length > 0) {
      result = {
        name: questionInfo,
      };
    } else {
      result = {
        name: q.questionContent,
      };
    }

    if (index !== -1) {
      const children = answerOptions.map((i) => {
        const { optionContent } = i;
        return {
          name: optionContent,
        };
      });

      result = { ...result, score: answerOptions[index].optionScore, children };
    }

    return result;
  }

  console.log('lose question:', no);

  return {
    name: `X-${no}`,
    score: '',
  };
};

const getMap = (answer) => {
  const map = {};
  answer.answerQuestions.forEach((i) => {
    map[i.questionNo] = i;
  });
  return map;
};

const sortingDefine = {
  'S0075:感官知觉领域': ['视觉应用', '听觉应用', '触觉应用', '味嗅觉刺激', '前庭及本体觉刺激'],
  'S0075:粗大动作领域': ['姿势控制', '转换姿势', '移动能力', '简单运动技能'],
  'S0075:精细动作领域': ['抓放能力', '操作能力', '简单劳作及书写技能'],
  'S0075:生活自理领域': ['饮食', '如厕', '清洁卫生', '穿著'],
  'S0075:语言沟通领域': ['言语机转', '语言理解', '口语表达', '沟通能力'],
  'S0075:认知领域': [
    '概念理解',
    '物体恒存概念',
    '简单因果概念',
    '基本物概念',
    '颜色概念',
    '形状概念',
    '比较概念',
    '空间概念',
    '符号概念',
    '数概念',
    '顺序概念',
    '模仿',
    '记忆',
    '配对分类',
    '逻辑思考',
    '解决问题',
    '简单阅读',
  ],
  'S0075:社会适应领域': ['自我概念', '环境适应', '人际互动', '游戏特质'],
};

const listToMap = (ary) => {
  const v = {};
  ary.forEach((item, index) => {
    v[item] = ary.length - index;
  });

  return v;
};

const sorting = (code, scaleName, scoringResults) => {
  const define = sortingDefine[`${code}:${scaleName}`];

  if (define) {
    const map = listToMap(define);
    // console.log(`define:${code}:${scaleName}`, 'map:', map);
    const sorted = scoringResults.sort((a, b) => {
      if (scaleName === '精细动作领域') {
        console.log(
          map[b.scoreName],b.scoreName,
          '-',
          map[a.scoreName],a.scoreName,
          '=',
          map[b.scoreName] - map[a.scoreName],
        );
      }

      return (map[b.scoreName] || 0) - (map[a.scoreName] || 0);
    });

    if (scaleName === '精细动作领域') {
      console.log('sorted:',sorted);
    }

    return sorted;
  }

  return [...scoringResults];
};

const getData = (code, reports, answers) => {
  const data = [];
  reports.forEach((report, i) => {
    const { scaleName, scoringResults } = report;
    const map = getMap(answers[i]);
    const item = {
      name: scaleName,
      children: [],
    };

    const parents = {};
    const sorted = sorting(code, scaleName, scoringResults);

    console.log('sorted:',sorted);

    sorted.forEach((result) => {
      const { scope, score, scoreName, questions } = result;

      console.log('scaleName:',scaleName);

      const sortQS = questions.sort((a, b) => {
        return a - b;
      });



      if (scope === 'TOTAL_SCORE') {
        item.score = score * 1; // 維度總分後台已經計算.不用再累加
      } else if (scope === 'DIMENSIONS') {
        const child = {
          name: scoreName,
          scope,
          score,
          children: sortQS.map((no) => {
            return getQuestion(map, no);
          }),
        };

        item.children.push(child);
      } else {
        const child = {
          name: scoreName,
          scope,
          score,
          children: questions.map((no) => {
            return getQuestion(map, no);
          }),
        };

        if (!parents[scope]) {
          parents[scope] = { score: 0, children: [] };
        }

        parents[scope].score = parents[scope].score + child.score * 1;
        parents[scope].children.push(child);
      }
    });

    Object.keys(parents).forEach((key) => {
      const v = parents[key];
      // 固定在第一位
      item.children.unshift({
        name: key,
        score: v.score,
        children: v.children,
      });
    });

    data.push(item);
  });

  return data;
};

function Result({ user = {}, readonly, print = false, evaluationAll }) {
  /**
   * 要帶出 S0062 和 SOO75 等綜合報告
   */
  const scaleCodes = ['S0062', 'S0075'];
  const [guide, setGuide] = useState();
  const [list, setList] = useState([]);

  const queryRecords = async (number) => {
    /**
     * 帶出最新一筆的綜合報告
     */
    const result = await findTopReport({ userNumber: number, codes: scaleCodes });

    if (result.length > 0) {
      const record = result[0];
      const data = await getGuide({ compose: record.scale, id: record.id, takeAnswer: truncate });
      setGuide(data);
      const newList = getData(data.code, data.reports, data.answers);
      console.log('newList', newList);
      setList(newList);
    } else {
      setList([]);
    }
  };

  useEffect(() => {
    if (user.visitingCodeV) {
      queryRecords(user.visitingCodeV);
    }
  }, [user.visitingCodeV]);

  const MAP = {
    S0062: [
      {
        key: 1,
        title: '综合发展',
        component: S0062_Chart1,
      },
      {
        key: 2,
        title: '感官知觉',
        component: S0062_Chart2,
      },
      {
        key: 3,
        title: '粗大动作',
        component: S0062_Chart3,
      },
      {
        key: 4,
        title: '精细动作',
        component: S0062_Chart4,
      },
      {
        key: 5,
        title: '生活自理',
        component: S0062_Chart5,
      },
      {
        key: 6,
        title: '沟通领域',
        component: S0062_Chart6,
      },
      {
        key: 7,
        title: '认知',
        component: S0062_Chart7,
      },
      {
        key: 8,
        title: '社会技能',
        component: S0062_Chart8,
      },
    ],
    S0075: [
      {
        key: 1,
        title: '综合发展',
        component: S0075_Chart1,
      },
      {
        key: 2,
        title: '感官知觉领域',
        component: S0075_Chart2,
      },
      {
        key: 3,
        title: '粗大动作领域',
        component: S0075_Chart3,
      },
      {
        key: 4,
        title: '精细动作领域',
        component: S0075_Chart4,
      },
      {
        key: 5,
        title: '生活自理领域',
        component: S0075_Chart5,
      },
      {
        key: 6,
        title: '语言沟通领域',
        component: S0075_Chart6,
      },
      {
        key: 7,
        title: '认知领域',
        component: S0075_Chart7,
      },
      {
        key: 8,
        title: '社会适应领域',
        component: S0075_Chart8,
      },
    ],
  };

  if (readonly) {
    let getReport = () => {
      if (guide && guide.code && list.length > 0) {
        let arr = MAP[guide.code];
        if (print) {
          return (
            <div className="print-page print-page-image">
              {arr.map((sub) => (
                <div key={sub.key}>
                  <sub.component
                    list={list}
                    guide={guide}
                    name={sub.title}
                    patientId={user.patientId}
                    onlyShowCanvas={readonly}
                  />
                  {sub.key !== 1 &&
                    evaluationAll.map((item) => {
                      return <>
                        <div>现状分析：{item.situation}</div>
                        <div>原因推断：{item.reason}</div>
                      </>;
                    })}
                </div>
              ))}
            </div>
          );
        } else {
          if (guide.code === 'S0062') {
            let first = arr.splice(0, 1); // 双溪的第一项是2个图表，这里单独拿出来作为一页
            const newArr = arrTrans(2, arr);
            return (
              <>
                <div className="page-title">姓名：{user.name}</div>
                <div className="page-title">编号：{user.caseCodeV}</div>
                <div className="page-title">量表类型：{guide.scaleName}</div>
                {first.map((sub, index) => (
                  <div
                    className="print-page print-page-image"
                    style={{ paddingTop: 0 }}
                    key={index}
                  >
                    <sub.component
                      key={sub.key}
                      list={list}
                      guide={guide}
                      name={sub.title}
                      patientId={user.patientId}
                      onlyShowCanvas={readonly}
                    />
                    <div className="page-number"></div>
                  </div>
                ))}
                {newArr.map((item, index) => (
                  <div
                    className="print-page print-page-image"
                    style={{ paddingTop: 0 }}
                    key={index}
                  >
                    {item.map((sub) => (
                      <sub.component
                        key={sub.key}
                        list={list}
                        guide={guide}
                        name={sub.title}
                        patientId={user.patientId}
                        onlyShowCanvas={readonly}
                      />
                    ))}
                    <div className="page-number"></div>
                  </div>
                ))}
              </>
            );
          } else {
            const newArr = arrTrans(2, arr);
            return (
              <>
                <div className="page-title">姓名：{user.name}</div>
                <div className="page-title">编号：{user.caseCodeV}</div>
                <div className="page-title">量表类型：{guide.scaleName}</div>
                {newArr.map((item, index) => (
                  <div className="print-page" key={index}>
                    {item.map((sub) => (
                      <sub.component
                        key={sub.key}
                        list={list}
                        guide={guide}
                        name={sub.title}
                        patientId={user.patientId}
                        onlyShowCanvas={readonly}
                      />
                    ))}
                    <div className="page-number"></div>
                  </div>
                ))}
              </>
            );
          }
        }
      }
      return <div />;
    };

    return getReport();
  }

  const getTabPane = () => {
    if (guide && guide.code && list.length > 0) {
      return MAP[guide.code].map((item) => (
        <Tabs.TabPane tab={item.title} key={item.key}>
          <item.component list={list} guide={guide} name={item.title} patientId={user.patientId} />
        </Tabs.TabPane>
      ));
    }
  };

  return (
    <>
      <Tabs defaultActiveKey={1}>{getTabPane()}</Tabs>
      {user.patientId && (
        <FooterToolbar>
          <Button
            type="primary"
            onClick={() => {
              printFile({
                url: `${location.origin}/print/P001?patientId=${user.patientId}`,
                // url: `http://training.cr.ts-health.cn/print/P001?patientId=${user.patientId}`,
                fileName: `${user.name}-${user.caseCodeV}-${guide.scaleName}`,
              });
            }}
          >
            打印
          </Button>
        </FooterToolbar>
      )}
    </>
  );
}

export default Result;
